package 算法.leetcode.linked.tree;

/**
 * @author lchenglong
 * @date 2020/12/18
 */
public class TreeBase {

    public class TreeNode {

        int val;

        TreeNode left;

        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public TreeNode create(Integer[] arr) {
        TreeNode root = new TreeNode(arr[0]);
        TreeNode cur = root,father = root;
        int index = 0;
        for (int i=1;i<arr.length;i++) {
            if (cur == null) {
                continue;
            }
            if ((2 * index + 1) <arr.length) {
                Integer val = arr[2 * index + 1];
                TreeNode left  = null;
                if (null != val) {
                    left = new TreeNode(val);
                }
                cur.left = left;
            }
            if ((2 * index + 2) <arr.length){
                Integer val = arr[2 * index + 2];
                TreeNode right = null;
                if (null != val) {
                    right = new TreeNode(val);
                }
                cur.right = right;
            }
            index++;
            if (index%2==1) {
                cur = father.left;
            } else {
                cur = father.right;
                father = father.left;
            }
        }
        return root;
    }

    public static void main(String[] args) {
        Integer[] arr = new Integer[]{6,2,8,0,4,7,9,null,null,3,5};
        TreeBase instance = new TreeBase();
        TreeNode root = instance.create(arr);
        instance.toString(root);
    }

    public void toString(TreeNode root) {
        if (root != null) {
            System.out.print(root.val + ",");
            toString(root.left);
            toString(root.right);
        }
    }
}
